package com.cy.pj.ajax.controller;

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
public class AjaxController {
    private List<Map<String,Object>> list = new ArrayList<>();
    public AjaxController(){
        Map<String,Object> map = new HashMap<>();
        map.put("id","100");
        map.put("name","华为");
        map.put("remark","very good");
        list.add(map);
    }
    @ResponseBody
    @PostMapping("/doAjaxPost")
    //@RequestMapping(value="/doAjaxPost",method = RequestMethod.POST)
    public String doAjaxPost(@RequestParam Map<String,Object> map){
        list.add(map);
        return "save ok";
    }
    @PutMapping("/doAjaxPut")
    @ResponseBody
    public String doAjaxPut(@RequestParam Map<String,Object> map){
        String id=(String)map.get("id");
        Iterator<Map<String,Object>> it=list.iterator();
        Map<String,Object> obj=null;
        while(it.hasNext()){
            obj=it.next();
            if(obj.get("id").equals(id))break;
        }
        obj.put("name", map.get("name"));
        obj.put("remark", map.get("remark"));
        return "update ok";
    }
    @ResponseBody
    @DeleteMapping("/doAjaxDelete/{id}")
    public String doAjaxDelete(@PathVariable Integer id){
        Iterator<Map<String,Object>> it=list.iterator();
        while (it.hasNext()){
            Map<String,Object> map =it.next();
            if (map.get("id").equals(String.valueOf(id)));
            it.remove();
        }
        return "delete ok";
    }
    @GetMapping("/doAjaxGet")
    @ResponseBody
    public List<Map<String,Object>> doAjaxGet(){
        return list;
    }
    @RequestMapping("/doNotAjaxUI")
    public String doNotAjaxUI(){
        return "not-ajax-01";
    }
    @RequestMapping("/doNotAjaxStart")
    public String doNotAjaxStart(Model model){
        model.addAttribute("result", "do not ajax request result");
        return "not-ajax-01";//请问这是局部刷新，还是全局
    }
    @RequestMapping("/doAjaxStart")
    @ResponseBody
    public String doAjaxStart(){
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "Response Result Of Ajax Get Request 01 ";
    }
}
